require( '$d/css/common.less' );
require('./style.less');
define( [
  'jquery',
  'require',
  'header',
  'message',
  'api',
  'pagination',
  'indusCategory',
  'bigwe_utils',
  'behavior',
  'searchMaterial',
  'constants'
], function( $, require ) {
  var bu = require( 'bigwe_utils' );

  var ShowTitleMessage = require( 'message' ),
    showTime = ShowTitleMessage.showTime,
    BIGWE_API = require( 'api' ),
    fieldCode = require( 'indusCategory' ),
    getUrlParam = bu.getUrlParam;
  var behavior = require( 'behavior' );
  var c = require( 'constants' );
  var searchMaterial = require( 'searchMaterial' );
  //$('.selectpicker').selectpicker('refresh');
  //点击到相应的页面
  searchMaterial.addClassByIndex( 3 );
  //$( '.search_area .search_item' ).eq( 3 ).addClass( 'selected' ).siblings().removeClass( 'selected' );
  $( '.fenlei_cate .choice' ).on( 'mouseenter', 'span', function( e ) {
    $( '.fenlei_more' ).fadeIn();
    e.stopPropagation();
  } );

  $( '.fenlei_more' ).mouseleave( function() {
    $( this ).fadeOut();
  } );

  var fjid = '';
  //行业选项
  for ( var key in fieldCode ) {
    if ( key.length == 4 ) {
      fjid = key;
      if ( key == '0215' ) {
        var str = '<li class="' + key + '"><span class="field-title-choice">' + fieldCode[ key ] + '</span></li>';
      } else {
        var str = '<li class="' + key + '"><div class="industry_cate"><span class="field-title">' + fieldCode[ key ] + '</span></div><div class="industry_list clearfix"></div></li>';
      }
      $( '.fenlei_more>ul' ).append( str );
    }
    if ( key.length == 6 ) {
      var str = '<span _value="' + key + '" class="field-title-choice">' + fieldCode[ key ] + '</span>';
      $( '.' + fjid + ' .industry_list' ).append( str );
    }
  }

  var search_type = 'gzh',
    search_key = getUrlParam( 'search_key' ),
    from_nav = getUrlParam( 'from_nav' ),
    isOk = true;
  search_key = search_key || '';
  if ( search_key != '' ) {
    var state = {
      search_type: search_type,
      search_key: search_key,
    };
    history.replaceState( state, document.title, '/search/account?search_key=' + search_key + '' );
  }
  // if(from_nav=='1'){
  //     $('.leixing_cate span:nth-child(2)').addClass('green').siblings().removeClass('green');
  //     $('.leixing_cate span:first-child').hide();
  // }
  //搜索接口
  var _search = {
    options: {
      key: decodeURI( search_key ),
      type: search_type,
      platform: $( '.leixing_cate span.green' ).attr( '_value' ),
      p: 1,
      l: 10,
    },
    init: function() {
      //this.result_list();
      this._filter();
      this.other_search();
      $( '.search_main .upper span' ).text() > 10 && this.paging( $( '.search_main .upper span' ).text() );
      //$( '.home_search_ipt .search_ipt' ).val( decodeURI( search_key ) );
      searchMaterial.setInputVal( decodeURI( search_key ), true );
    },
    result_list: function( _parameter ) {
      var html_list = '',
        source_icon = '',
        _this = this;
      if ( search_key == '' ) {
        $( '.from_nav_0' ).hide();
        $( '.from_nav_1' ).show();
      } else {
        $( '.from_nav_1' ).hide();
        $( '.from_nav_0' ).show();
      }
      if ( this.options.platform == '' || this.options.platform == undefined ) {
        $( '.leixing_cate span:not(:hidden)' ).eq( 0 ).addClass( 'green' ).siblings().removeClass( 'green' );
      }
      ShowTitleMessage.show( '正在加载' );
      $.ajax( {
        type: "post",
        dataType: "json",
        url: BIGWE_API.SEARCH.SEARCH_LIST,
        data: this.options,
        success: function( data ) {
          if ( data.ret == 0 ) {
            var _parameter = data.data.data;
            var totalNumber = data.data.total_rows;
            if ( isOk == true ) {
              $( '#article_paging' ).hide();
            }
            //账户列表
            for ( var i in _parameter ) {
              var publisher_html = '';
              //数据缺少字段
              var account_data = {};
              account_data.alias = _parameter[ i ].alias || '';
              account_data.biz = _parameter[ i ].biz || '';
              account_data.category_code = _parameter[ i ].category_code || '';
              account_data.data_time = _parameter[ i ].data_time || '';
              account_data.hd_head_img = _parameter[ i ].hd_head_img || '';
              account_data.nick_name = _parameter[ i ].nick_name || '';
              account_data.nickname_simple = _parameter[ i ].nickname_simple || '';
              account_data.pkey = _parameter[ i ].pkey || '';
              account_data.round_head_img = _parameter[ i ].round_head_img || '';
              account_data.signature = _parameter[ i ].signature || '';
              account_data.source = _parameter[ i ].source || '';
              account_data.user_name = _parameter[ i ].user_name || '';
              //var account_data = _parameter[ i ];
              var source_icon = null;
              var platform = null;
              if ( account_data.source == 'bigwe.com' ) {
                source_icon = 'icon-iconbigwe'
                platform = ' bigwe'
              } else if ( account_data.source == 'toutiao.com' ) {
                source_icon = 'icon-icontoutiao'
                platform = ' toutiao'
              } else if ( account_data.source == 'mp.weixin.qq.com' ) {
                source_icon = 'icon-weixin'
                platform = ' weixin'
              }
              //高亮
              var _nickname = account_data.nick_name;
              var wx_account = null;
              var _describe = null;
              var participle = data.data.words;
              var search_wz = null;
              if ( participle.length == 0 ) {
                search_wz = $( '.search_ipt' ).val();
                if ( search_wz != '' ) {
                  _nickname = _nickname.replace( new RegExp( bu.regExpReplace( search_wz ), "g" ), '<em class="green">' + search_wz + '</em>' );
                }
              } else {
                for ( var j in participle ) {
                  _nickname = _nickname.replace( new RegExp( bu.regExpReplace( participle[ j ] ), "g" ), '<em class="green">' + participle[ j ] + '</em>' );
                }
              }
              html_list += '<div class="acut_sol' + platform + '" biz="' + account_data.user_name + '">' +
                '<div class="profile"><img src="' + ( ( account_data.hd_head_img == undefined || account_data.hd_head_img == 'null' || account_data.hd_head_img == '' ) ? c.resPath + '/images/default_user_face.png' : account_data.hd_head_img ) + '" alt=""></div>' +
                '<div class="public_info' + ( account_data.source == 'mp.weixin.qq.com' ? '' : ' margin_t' ) + '">'
              if ( account_data.source == 'mp.weixin.qq.com' ) {
                wx_account = account_data.alias;
                _describe = ( account_data.signature.length > 90 ? account_data.signature.substr( 0, 90 ) + '...' : account_data.signature );
                if ( participle.length == 0 ) {
                  search_wz = $( '.search_ipt' ).val();
                  if ( search_wz != '' ) {
                    var regstr = new RegExp( bu.regExpReplace( search_wz ), "g" );
                    wx_account = wx_account.replace( regstr, '<em class="green">' + search_wz + '</em>' );
                    _describe = _describe.replace( regstr, '<em class="green">' + search_wz + '</em>' );
                  }
                } else {
                  var regexp = new RegExp( bu.regExpReplace( participle[ j ] ), "g" );
                  for ( var j in participle ) {
                    wx_account = wx_account.replace( regexp, '<em class="green">' + participle[ j ] + '</em>' );
                    _describe = _describe.replace( regexp, '<em class="green">' + participle[ j ] + '</em>' );
                  }
                }
                html_list += '<p class="public_mz"><span class="iconfont ' + source_icon + '"> </span><a target="_blank" href="/profile?biz=' + account_data.biz + '&gn=' + escape( account_data.nick_name ) + '&platform=mp.weixin.qq.com">' + _nickname + '</a></p>' +
                  '<p class="public_zh">微信号：' + wx_account + '</p>' +
                  '<p class="public_gn">功能介绍：' + _describe + '</p>'
              } else if ( account_data.source == 'toutiao.com' ) {
                _describe = ( account_data.signature.length > 90 ? account_data.signature.substr( 0, 90 ) + '...' : account_data.signature );
                if ( participle.length == 0 ) {
                  search_wz = $( '.search_ipt' ).val();
                  if ( search_wz != '' ) {
                    _describe = _describe.replace( new RegExp( search_wz, "g" ), '<em class="green">' + search_wz + '</em>' );
                  }
                } else {
                  for ( var j in participle ) {
                    _describe = _describe.replace( new RegExp( participle[ j ], "g" ), '<em class="green">' + participle[ j ] + '</em>' );
                  }
                }
                html_list += '<p class="public_mz"><span class="iconfont ' + source_icon + '"> </span><a target="_blank" href="/profile?biz=' + account_data.biz + '&gn=' + escape( account_data.nick_name ) + '&platform=toutiao.com">' + _nickname + '</a></p>' +
                  '<p class="public_gn">介绍&nbsp;:&nbsp;' + _describe + '</p>'
              } else if ( account_data.source == 'bigwe.com' ) {
                html_list += '<p class="public_mz"><span class="iconfont ' + source_icon + '"> </span><a target="_blank" href="/profile?biz=' + escape( account_data.nick_name ) + '&gn=' + escape( account_data.nick_name ) + '&platform=bigwe.com">' + _nickname + '</a></p>' +
                  '<p class="public_gn" style="' + ( account_data.fir_industry == null ? 'display:none' : 'display:block' ) + '">行业&nbsp;:&nbsp;' + account_data.fir_industry + '&nbsp;&nbsp;&nbsp;&nbsp;' + account_data.sec_industry + '</p>'
              }
              html_list += '</div>' +
                '<button type="button" class="btn btn-default subscribe pull-right">订阅</button>' +
                '</div>'
            }
            if ( _parameter.length == 0 ) {
              $( '.search_account' ).empty().append( '<p class="no_content"><span class="glyphicon glyphicon-flash"></span>暂无内容</p>' );
            } else {
              $( '.search_account' ).empty().append( html_list );
            }

            $( '.search_main .upper span' ).text( totalNumber )
            if ( isOk == true && totalNumber > 10 ) {
              //totalNumber>500?totalNumber=500:totalNumber;
              _this.paging( totalNumber );
            }
          } else {
            ShowTitleMessage.showWarning( '请输入搜索内容', showTime );
          }
        },
        complete: function() {
          ShowTitleMessage.hide();
        }
      } );
    },
    _filter: function() {
      var _this = this;
      $( '.fenlei_more' ).on( 'click', '.industry_list span,span.fenlei_all', function() {
        $( '.fenlei_cate .choice span' ).replaceWith( this.outerHTML );
        $( '.fenlei_cate .choice span' ).addClass( 'green' );
        _this.options.cc = $( this ).attr( '_value' );
        _this.options.p = 1;
        isOk = true;
        _this.result_list();
        $( this ).parents( '.fenlei_more' ).fadeOut();
      } );
      $( '.leixing_cate' ).on( 'click', 'span', function() {
        $( this ).addClass( 'green' ).siblings().removeClass( 'green' );
        _this.options.platform = $( this ).attr( '_value' );
        _this.options.p = 1;
        isOk = true;
        _this.result_list();
      } );
    },
    other_search: function() {
      //无刷新替地址
      var _this = this;
      searchMaterial.onSearch = function( search_key_in ) {
        search_type = 'gzh';
        search_key = search_key_in;
        if ( search_key != '' ) {
          _this.options.key = search_key;
          _this.options.type = search_type
          _this.options.p = 1;
          isOk = true;
          _this.result_list();
          var state = {
            search_type: search_type,
            search_key: search_key,
          };
          // sherlockl 运营数据统计
          behavior.addRecord( {
            category: behavior.searchGzh,
            action: search_key
          } );

          history.replaceState( state, document.title, '/search/account?search_key=' + search_key + '' );

        }
        
      }
      /*$( '.home_search_ipt button' ).click( function( e ) {

      } );*/
      // 同图片搜索
      /* $( '.home_search_ipt .search_ipt' ).bind( 'keypress', function( event ) {
        search_type = $( '.header_container_main .search_area .search_item.selected' ).attr( 'kw' );
        search_key = $( '.home_search_ipt .search_ipt' ).val();
        if ( event.keyCode == "13" ) {
          if ( $( '.search_ipt' ).val() != '' ) {
            event.stopImmediatePropagation();
            event.preventDefault();
            _this.options.key = search_key;
            _this.options.type = search_type
            _this.options.p = 1;
            isOk = true;
            _this.result_list();
            var state = {
              search_type: search_type,
              search_key: search_key,
            };
            history.replaceState( state, document.title, '/search/account?search_key=' + search_key + '' );
          }
        }
      } ); */
      searchMaterial.setInputVal( decodeURI( search_key ), true );
      //$( '.home_search_ipt .search_ipt' ).val( decodeURI( search_key ) );
      window.addEventListener( 'popstate', function( e ) {
        if ( history.state ) {
          var state = e.state;
          _this.options.key = state.search_key;
          _this.options.type = state.search_type
          _this.options.p = 1;
          isOk = true;
          _this.result_list();
          $( '.home_search_ipt .search_ipt' ).val( decodeURI( state.search_key ) );
        } else {
          window.location.reload();
        }
      }, false );
    },
    paging: function( _parameter ) {
      var _this = this;
      $( "#article_paging" ).pagination( _parameter, {
        num_edge_entries: 1,
        num_display_entries: 8,
        items_per_page: 10,
        link_to: 'javascript:window.scrollTo(0,0);',
        prev_text: '上一页',
        next_text: '下一页',
        callback: function( _index, jq ) {
          if ( isOk == true ) {
            isOk = false;
            return;
          } else {
            _this.options.p = _index + 1;
            _this.result_list();
          }
        }
      } );
      $( '#article_paging' ).show();
    }
  }
  _search.init();
  $( '.leixing_cate span:not(:hidden)' ).eq( 0 ).addClass( 'green' ).siblings().removeClass( 'green' );
  //二维码生成
  $( ".search_account" ).on( 'mouseenter', '.acut_sol.weixin', function( e ) {
    e.stopPropagation();
    subscribe( $( this ).find( '.subscribe' ).get( 0 ) );
  } );
  $( ".search_account" ).on( 'mouseleave', '.acut_sol.weixin', function( e ) {
    e.stopPropagation();
    $( '.subscribe_qr' ).remove();
  } );

  function subscribe( a ) {
    $( '.subscribe_qr' ).remove();
    var g = document.createElement( "div" );
    g.className = 'subscribe_qr';
    g.style.top = ( a.offsetTop + a.offsetHeight + 45 ) + 'px';
    g.style.left = ( a.offsetLeft - 19 ) + 'px';
    g.style.opacity = 0.3;
    g.innerHTML = '<img src="http://open.weixin.qq.com/qr/code/?username=' + $( a ).parents( '.acut_sol' ).attr( 'biz' ) + '" alt="二维码加载失败..." />';
    $( a ).parents( '.acut_sol' ).append( g );
    //document.body.appendChild(g);
    $( '.subscribe_qr' ).animate( {
      top: ( a.offsetTop + a.offsetHeight + 15 ) + 'px',
      opacity: 1
    }, 700, 'easeout' );

    $( document ).bind( "click.subscribe_qr", function( e ) {
      $( '.subscribe_qr' ).remove();
      $( document ).unbind( 'click.subscribe_qr' );
    } );
  }
} )